package com.tenton.netty.multicast;

import com.tenton.netty.config.NettyConfig;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.Channel;
import io.netty.channel.ChannelOption;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.DatagramPacket;
import io.netty.channel.socket.nio.NioDatagramChannel;
import org.springframework.stereotype.Component;

import java.net.InetSocketAddress;

/**
 * @ClassName: UdpClient
 * @Description： 组播客户端
 * @Author： tangdong
 * @Date： 2024/6/25
 */
@Component
public class UdpClient {

    public void sendMessage(byte[] data) {
        // 配置客户端
        NioEventLoopGroup group = new NioEventLoopGroup();
        try {
            Bootstrap b = new Bootstrap();
            b.group(group)
                    .channel(NioDatagramChannel.class)
                    // 如果需要广播，请启用此选项
                    .option(ChannelOption.SO_BROADCAST, true)
                    .handler(new UdpClientHandler());
            Channel ch = b.bind(0).sync().channel();
            ch.writeAndFlush(new DatagramPacket(
                    ch.alloc().buffer().writeBytes(data),
                    new InetSocketAddress(NettyConfig.pubIp, NettyConfig.pubPort))
            );
            ch.close();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            // 关闭事件循环组
            group.shutdownGracefully();
        }
    }
}
